<template>
  <el-container>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div style="display: flex;flex-direction: row;justify-content: space-between;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: flex-end;">
            <div class="report_header_date">
              <el-date-picker
                style="width: 100%;"
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </div>
            <div class="report_header_query">
              <queryShop @queryShopClick='queryShopClick'></queryShop>
            </div>
            <div class="report_header_query" style="width:150px;">
              <el-select v-model="query.vipId" clearable placeholder="会员等级">
                <el-option
                  v-for="item in vipList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.vip"
                ></el-option>
              </el-select>
            </div>
            <div class="report_header_query">
              <el-select v-model="memberQuery" placeholder="客户" value-key="id"  filterable :filter-method="queryMember"
                         clearable @change="selectMember">
                <el-option v-for="item in memberOptions" :key="item.id" :label="item.name" :value="item" >
                  <div style="display: flex">
                    <span style="width: 60px;">{{item.code}}</span>
                    <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{ item.mobile }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchMember">搜索客户</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
            </div>
            <div class="report_header_query"  style="width:150px;">
              <el-select v-model="query.paymentPluginId" clearable placeholder="结算方式">
                 <el-option label="现金客户" value="cashPayPlugin"></el-option>
                 <el-option label="月结客户" value="debtPayPlugin"></el-option>
                 <el-option label="代销客户" value="salePayPlugin"></el-option>
              </el-select>
            </div>
          </div>
          <div style="display:flex">

          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="add()"
                     v-permission="['receivable.add']">新增收款</el-button>
          <ExportList2Excel style='margin-top: 5px;' ref="exportList2Excel" @handleExport="handleExport" name="导出" />
          </div>
        </div>
      </div>
    </el-header>
    <div class="pd10">
      <el-table ref="receivableTable" v-loadMore="[Math.random(), 'receivable-list']" :height="curHeight" :data="receivableList" border stripe :span-method="totalLine">
        <el-table-column label="排序" align="center" type="index" width="50%">
            <template slot-scope="scope">{{ scope.$index == receivableList.length-1?'总计':scope.$index +1}}</template>
        </el-table-column>
        <el-table-column label="客户编号" header-align="center" align="left" prop="memberCode" width="100" />
        <el-table-column label="客户名称" header-align="center" align="left" prop="memberName" width="200"  />
        <el-table-column label="结算方式" header-align="center" align="left" prop="paymentPluginName" width="100"/>
        <el-table-column label="联系电话" header-align="center" align="center" prop="mobile" width="120" />
        <el-table-column label="应收金额" header-align="center" align="right" prop="amount" width="100" />
        <el-table-column label="已收金额" header-align="center" align="right" prop="amountPaid" width="100" />
        <el-table-column label="未收金额" header-align="center" align="right" width="80" prop="restAmount" />

        <el-table-column label="地址" header-align="center" align="left" prop="address" />
        <el-table-column label="功能" header-align="center"  align="center" width="120">
          <template slot-scope="scope" v-if="scope.$index != receivableList.length-1">
            <el-button v-permission="['payment.add']" type="primary" round size="mini" @click="showDialog(scope.row)">收款</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center"  label="查看详情" >
          <template slot-scope="scope">
            <div class="justify_right shop_Height"  @click="clicklook(scope.row)">
              <a class="details_Title">明细详情</a>
            </div>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadReceivable" />
    </el-footer>

    <el-dialog
      title="双击选择客户"
      :visible.sync="memberTableVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="memberTableClose">
      <div style="position: relative;">
        <member-table :key="times" @memberDouble="memberDouble" @memberTableClose="memberTableClose"></member-table>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import ExportList2Excel from "@/components/ExportList2Excel";
  import {mapGetters} from 'vuex'
  import memberTable from '@/components/MemberTable/index'
  import loadMore from '@/utils/loadMore.js'
  import { EventBus } from '@/api/eventBus'
  import {selectCountList,summary } from '@/api/receivable'
  import { list as memberList } from '@/api/member'
  import {list as vipList} from "@/api/vip";
  import Pagination from '@/components/Pagination'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import utils from '../../utils/utils.js'
  import queryShop from '@/components/Query/queryShop'

  import {
    getMenuTree
  } from '@/api/sysMch.js'
  export default {
    name: 'receivable-list',
    directives: { loadMore, permission ,elDragDialog},
    components: { Pagination,memberTable,ExportList2Excel,      queryShop,
    },

    data() {
      return {
        printing:5000,//打印数量设置
        receivableList: [],
        memberQuery:'',
        queryType: true,
        total: 0,
        type: 0,
        pageNum: 1,
        pageSize: 20,
        memberName: '',
        memberOptions: [],
        memberTableVisible:false,
        memberMark: false,
        paymentPluginName: '',
        form: {},
        times:'',
        selectionChange: [],
        vipList:[],
        curHeight: null,
        queryClicked: false,
        query: {
          memberId: '',
          verifyId:'',
          sn:'',
          date: [],
          vipId:'',
          paymentPluginId:''
        },
        pickerOptions: {// 时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created() {
      this.loadReceivable();
      this.queryMember();
      this.loadVip();
      EventBus.$on('receivable-add', res => { // 监听新增完毕
        this.loadReceivable();
      });
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    computed: {
      ...mapGetters([
        'scopeType'
      ])
    },
    methods: {
          handleExport() {
        let _this = this
        var loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let data = {}
        data.tHeader = ["客户编号", "客户名称", "结算方式", "联系电话", "应收金额", "已收金额", '未收金额','会员地址']
        data.filterVal = ["memberCode","memberName",  "paymentPluginName", "mobile","amount", "amountPaid", 'restAmount','address']
        data.filename = "应收款汇总表";
            const keyword = Object.assign({}, this.query)
            if(utils.isNull(keyword.date)){
              keyword.date = []
            }
            const params = new URLSearchParams()
            params.append('pageNum', this.pageNum)
            params.append('pageSize', this.printing)
            params.append('memberId', keyword.memberId)
            params.append('vipId', keyword.vipId)
            params.append('paymentPluginId', keyword.paymentPluginId)
            params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
            params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        selectCountList(params).then(res => {
          data.list = res.data.data
          summary().then(res=>{
           if(res.data[0]!=null&&res.data.length>0){

             this.$set(res.data[0],"memberId","合计")

            data.list.push(res.data[0])
            _this.$refs.exportList2Excel.handleDownload(data);}
            loading.close();
          })

         if(data.list.length==this.printing){
            this.pageNum++
             console.log(this.pageNum);
             this.handleExport()
          }
          else{
            return;
          }
        }).catch(error => {
          _this.$refs.exportList2Excel.unlockLoading()
          loading.close();
          console.log('error!!')
        })
      },
      queryShopClick(data) {
        console.log(data)
        this.query.shopId = data.shopId
        this.shopname=data.name
      },
      memberDouble(data){
        this.memberQuery=data.name
        this.query.memberId=data.id
        this.memberTableVisible = false
      },
      memberTableClose(){
        this.memberTableVisible = false
      },
      toSearchMember() {
        this.times=new Date().getSeconds()
        this.memberTableVisible = true
      },
      clicklook(item){
        this.$router.push({
          path: '/receivable/detail',
          query: {
            beginDate:this.query.beginDate ,
            endDate:this.query.endDate,
            vipId:this.query.vipId,
            paymentPluginId:this.query.paymentPluginId,
            shopId:this.query.shopId,
            shopname:this.shopname,
            membername:item.memberName,
            memberId:item.memberId
          }
        })
      },
      selectMember(data){
        if(!utils.isNull(data)){
          this.memberQuery=data.name
          this.query.memberId=data.id
        }else{
          this.query.memberId=''
        }
      },
        summaryClick() {
        var _this = this
        const keyword = Object.assign({}, this.query)
          if(utils.isNull(keyword.date)){
            keyword.date = []
          }
        const params = new URLSearchParams()
        params.append('memberId', keyword.memberId)
        params.append('vipId', keyword.vipId)
        params.append('paymentPluginId', keyword.paymentPluginId)
        params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
        params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        summary(params).then(response => {
           if(response.data[0]!=null&&response.data.length>0){

            _this.receivableList.push(response.data[0])

             console.log(_this.receivableList)
        }
        }).catch(error => {})
      },
      loadReceivable() {
        const keyword = Object.assign({}, this.query)
        if(utils.isNull(keyword.date)){
          keyword.date = []
        }
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.pageSize)
        params.append('memberId', keyword.memberId)
        params.append('vipId', keyword.vipId)
        params.append('paymentPluginId', keyword.paymentPluginId)
        params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
        params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        return new Promise((resolve, reject) => {
          selectCountList(params).then(res => {
            this.total = res.data.total
            this.receivableList = res.data.data;
            this.summaryClick()
            resolve()
          })
        })
      },
      showDialog(data) {

        this.$router.push({
          path:"/receivable/add",
          query:{
            paymentPluginId:'cashPayPlugin',
            paymentPluginName:'现金',
            memberId:data.memberId,
            memberName:data.memberName ,
            //id:data.id
          }
        })
      },
      queryMember(query) {
        clearTimeout(this.memberMark)
        this.memberMark = setTimeout(() => {
          memberList({ keyword: query }).then(res => {
            this.memberOptions = res.data.data
          }).catch(err => { console.log(err) })
        }, 500)
      },
      queryClick() {
        this.queryClicked = true
        this.pageNum = 1
        this.loadReceivable().then(() => { this.queryClicked = false })
      },
      beforeMount() {
        window.onresize = () => {
          return (() => {
            const h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              this.curHeight = h - 266// 减去页面上固定高度height
            } else {
              this.curHeight = h - 220// 减去页面上固定高度height
            }
          })()
        }
      },
      loadVip(){
        let params = new URLSearchParams();
        params.append('pageSize', 2000);
        vipList(params).then(response =>{
          this.vipList=response.data.data
        }).catch(error=>{
          console.log('error!!')
        })
      },
      comeIn() {
        const h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        const h = document.documentElement.clientHeight || document.body.clientHeight
        if (this.queryType === false) {
          this.curHeight = h - 266// 减去页面上固定高度height
        } else {
          this.curHeight = h - 220// 减去页面上固定高度height
        }
      },

      add(){
        this.$router.push({
          path: '/receivable/add'
        })
      },
      totalLine({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        var _this = this
        if (rowIndex === _this.receivableList.length - 1) {
          if (columnIndex === 0) {
            return {
              rowspan: 1,
              colspan: 4
            };
          } else if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      },
    }
  }
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
          padding: 10px;
          /* height: 100% !important; */
          padding-bottom: 0;
        }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
